package org.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.dao.UserDao;
import org.json.simple.JSONValue;
import org.model.User;
import org.service.UserService;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TimeZone;

/**
 * Created by tedzy on 2015/5/12.
 * 用户注册、登录动作
 */
public class userAction extends ActionSupport {
    private String jsonResult;
    private String username;
    private String password;
    private String newPassword;
    private String email;
    private UserService userService;
    private String content;
    private User user;
    private String newavatar;
    private DateFormat sdf;

    /**
     * 注册用户。
     * URL: /user/register.json
     * 需要传入username，password和email
     * @return result：success表示注册成功，error表示注册失败。
     *          info：error时有效，表示失败信息
     */
    public String register() {
        Map<String, Object> json = new LinkedHashMap<>();
        boolean check = true;
        //用户名不能为空
        if(username == null || username.equals("")){
            json.put("result", "error");
            json.put("info", "用户名不能为空。");
            check = false;
        }
        //密码不能为空
        if(password == null || password.equals("")){
            json.put("result", "error");
            json.put("info", "密码不能为空。");
            check = false;
        }
        //用户名查重
        if(userService.countUsername(username)!=0){
            json.put("result", "error");
            json.put("info", "用户名已存在。");
            check = false;
        }
        if(check){
            User user = new User();
            user.setUsername(username);
            user.setPassword(UserDao.encryptPassword(password));
            user.setEmail(email);
            if(userService.addUser(user)){
                json.put("result", "success");
                json.put("info", "success");
            }else{
                json.put("result", "error");
                json.put("info", "数据库出错。");
            }
        }
        jsonResult = JSONValue.toJSONString(json);
        return SUCCESS;
    }

    /**
     * 登录。
     * URL: /user/login.json
     * 传入：username, password
     * @return result: success 登录成功, error 登录错误
     *          info: 错误时表示错误信息
     */
    public String login(){
        Map<String, Object> json = new LinkedHashMap<>();
        Map<String, Object> session = ActionContext.getContext().getSession();
        boolean check = true;
        //判断是否已经登录
        Object isLogin = session.get("login_status");
        if(isLogin != null && (boolean) isLogin){
            json.put("result", "error");
            json.put("info", "您已经登录。");
            check = false;
        }
        //用户名不能为空
        if(username == null || username.equals("")){
            json.put("result", "error");
            json.put("info", "用户名不能为空。");
            check = false;
        }
        //密码不能为空
        if(password == null || password.equals("")){
            json.put("result", "error");
            json.put("info", "密码不能为空。");
            check = false;
        }
        if(check){
            String pass = UserDao.encryptPassword(password);
            User user = userService.checkLogin(username, pass);
            if(user==null){
                json.put("result", "error");
                json.put("info", "用户名与密码不匹配。");
            }else{
                session.put("login_status", true);
                session.put("login_user", user);
                json.put("result", "success");
                json.put("info", "success");
            }
        }

        jsonResult = JSONValue.toJSONString(json);
        return SUCCESS;
    }

    /**
     * 判断是否登录。
     * URL: /user/isLogin.json
     * 无需传入参数
     * @return status: true 已登录， false 未登录
     *          uid: ID 登录状态下表示登录用户，未登录用户不存在，下同
     *          username: 用户名
     *          email: E-mail
     */
    public String isLogin(){
        Map<String, Object> json = new LinkedHashMap<>();
        Map<String, Object> session = ActionContext.getContext().getSession();
        Object lsObj = session.get("login_status");
        if(lsObj != null && (boolean) lsObj){
            User user = (User)session.get("login_user");
            json.put("uid", user.getId());
            json.put("username", user.getUsername());
            json.put("email", user.getEmail());
            json.put("status", true);
        }else{
            json.put("status", false);
        }
        jsonResult = JSONValue.toJSONString(json);
        return SUCCESS;
    }

    /**
     * 注销。
     * URL: /user/logout.json
     * 无需参数
     * @return result: success 注销成功, error 注销错误
     *          info: 错误时表示错误信息
     */
    public String logout(){
        Map<String, Object> json = new LinkedHashMap<>();
        Map<String, Object> session = ActionContext.getContext().getSession();
        Object isLogin = session.get("login_status");
        if(isLogin != null && (boolean) isLogin){
            session.put("login_status", false);
            session.put("login_user", null);
            json.put("result", "success");
            json.put("info", "成功注销。");
        }else{
            json.put("result", "error");
            json.put("info", "您没有登录，无需注销。");
        }
        jsonResult = JSONValue.toJSONString(json);
        return SUCCESS;
    }

    /**
     * 修改密码。
     * URL: /user/resetpassword.json
     * 输入： password 原密码， newpassword 新密码
     * @return result error 修改失败, success 修改成功
     *          info result为error时显示错误原因
     */
    public String resetPassword() {
        Map<String, Object> json = new LinkedHashMap<>();
        Map<String, Object> session = ActionContext.getContext().getSession();
        Boolean check = true;
        //判断是否已经登录
        Object isLogin = session.get("login_status");
        if(isLogin == null || !(boolean) isLogin){
            json.put("result", "error");
            json.put("info", "您还没登录。");
            check = false;
        }
        //密码不能为空
        if(password == null || password.equals("")){
            json.put("result", "error");
            json.put("info", "原密码不能为空。");
            check = false;
        }
        if(newPassword == null || newPassword.equals("")){
            json.put("result", "error");
            json.put("info", "新密码不能为空。");
            check = false;
        }
        //原密码等于当前用户的密码
        User user = (User)session.get("login_user");
        if (!UserDao.encryptPassword(password).equals(user.getPassword())) {
            json.put("result", "error");
            json.put("info", "原密码错误。");
            check = false;
        }
        if (check) {
            user.setPassword(UserDao.encryptPassword(newPassword));
            userService.update(user);
            json.put("result", "success");
        }
        jsonResult = JSONValue.toJSONString(json);
        return SUCCESS;
    }

    public String setAvatar(){
        Map<String, Object> json = new LinkedHashMap<>();
        Map<String, Object> session = ActionContext.getContext().getSession();
        Boolean check = true;
        //判断是否已经登录
        Object isLogin = session.get("login_status");
        if(isLogin == null || !(boolean) isLogin){
            json.put("result", "error");
            json.put("info", "您还没登录。");
            check = false;
        }
        if(newavatar == null || newavatar.equals("")){
            json.put("result", "error");
            json.put("info", "新头像地址不能为空。");
            check = false;
        }
        User user = (User)session.get("login_user");
        if (check) {
            user.setAvatar(newavatar);
            userService.update(user);
            json.put("result", "success");
        }
        jsonResult = JSONValue.toJSONString(json);
        return SUCCESS;
    }

    public String userHome(){
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        Map<String, Object> session = ActionContext.getContext().getSession();
        //判断是否已经登录
        Object isLogin = session.get("login_status");
        if(isLogin == null || !(boolean) isLogin){
            jsonResult = "未登录。";
            content = "/login";
            return ERROR;
        }
        user = (User) session.get("login_user");
        return SUCCESS;
    }

    public String getJsonResult() {
        return jsonResult;
    }

    public void setJsonResult(String jsonResult) {
        this.jsonResult = jsonResult;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getNewavatar() {
        return newavatar;
    }

    public void setNewavatar(String newavatar) {
        this.newavatar = newavatar;
    }

    public DateFormat getSdf() {
        return sdf;
    }

    public void setSdf(DateFormat sdf) {
        this.sdf = sdf;
    }
}